<script lang="ts" setup>
import { ref, watch, onMounted, reactive } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { NLayout, NLayoutHeader, NLayoutContent, NSpace, NIcon, NButtonGroup, NButton, NPopover, NTabs, NTab, NModal, NCard, NForm, NFormItem, NInput, NSelect, NPopconfirm, useNotification } from 'naive-ui'
import type { FormInst, FormRules } from 'naive-ui'
import { LeftOutlined, SaveOutlined, SendOutlined, ArrowsAltOutlined, ShrinkOutlined, EditOutlined, EllipsisOutlined, CloseOutlined } from '@vicons/antd'
import http from '@/tools/http'
import { useConfigStore } from '@/stores/configStore'
import { useUserStore } from '@/stores/userStore'
import { useFlowStore } from './flowStore'

import ModelConfig from './model-config/index.vue'
import FlowDesigner from '@/views/workflow/component/flow-designer/index.vue'
import FormDesigner from '@/views/workflow/component/form-designer/index.vue'
import ExtConfig from './ext-config/index.vue'
import FormViewer from '../component/form-viewer/index.vue'
import ApproveForm from './approve-form/index.vue'
import FlowMessage from './flow-message/index.vue'
import UserSelector from './user-selector/index.vue'

const router = useRouter()
const route = useRoute()
const configStore = useConfigStore()
const userStore = useUserStore()
const flowStore = useFlowStore()
const notification = useNotification()

const pageFullScreen = ref<boolean>(false)

const visiable = reactive({
    approveForm: false,
    rollbackForm: false,
    taskAddUserForm: false,
    taskTransferForm: false
})

const rollbackFormRef = ref<FormInst | null>(null)

const rollbackForm = reactive({
    instanceId: "",
    taskId: "",
    nodeId: 1,
    rollbackMessage: ""
})

const rollbackFormRules: FormRules = {
    nodeId: {
        type: 'number',
        required: true,
        message: '请选择流程退回节点',
        trigger: ['input']
    }
}

const taskAddUserForm = reactive<{
    instanceId: string
    taskId: string
    userIdSet: string[]
    message: string
}>({
    instanceId: "",
    taskId: "",
    userIdSet: [],
    message: ""
})

const taskTransferForm = reactive<{
    instanceId: string
    taskId: string
    userIdSet: string[]
    message: string
}>({
    instanceId: "",
    taskId: "",
    userIdSet: [],
    message: ""
})

watch(configStore.getTheme, (newValue: any, oldValue: any) => {
    if (newValue) {
        document.getElementById("design-header")?.style.setProperty('--flame-icon-background-color', 'rgba(255, 255, 255, .16)');
    } else {
        document.getElementById("design-header")?.style.setProperty('--flame-icon-background-color', 'rgba(0, 0, 0, .16)');
    }
})

onMounted(() => {
    if (configStore.theme === 'darkTheme') {
        document.getElementById("design-header")?.style.setProperty('--flame-icon-background-color', 'rgba(255, 255, 255, .16)');
    } else {
        document.getElementById("design-header")?.style.setProperty('--flame-icon-background-color', 'rgba(0, 0, 0, .16)');
    }
})

function openApproveForm() {
    visiable.approveForm = true
}

function openRollbackForm() {
    rollbackForm.instanceId = route.query.instanceId as string
    rollbackForm.taskId = route.query.taskId as string
    rollbackForm.nodeId = 1
    rollbackForm.rollbackMessage = ""
    visiable.rollbackForm = true
}

function openTaskAddUserForm() {
    taskAddUserForm.userIdSet.length = 0
    visiable.taskAddUserForm = true
}

function openTaskTransferForm() {
    taskTransferForm.userIdSet.length = 0
    taskTransferForm.message = ""
    visiable.taskTransferForm = true
}

function rollbackFormSubmit() {
    rollbackFormRef.value?.validate((errors) => {
        if (!errors) {
            http.post("/workflow/ru/instance/rollback-to-node", rollbackForm).then(({ data }) => {
                if (data.code === "0") {
                    visiable.rollbackForm = false
                    notification['success']({
                        content: '流程退回成功',
                        meta: `${data.msg}`,
                        duration: 2500,
                        keepAliveOnHover: true
                    })
                }
            })
        }
    })
}

function taskAddUserFormSubmit(userIdList: string[]) {
    if (userIdList.length > 0) {
        taskAddUserForm.instanceId = route.query.instanceId as string
        taskAddUserForm.taskId = route.query.taskId as string
        taskAddUserForm.userIdSet = userIdList
        http.post("/workflow/ru/instance/task/add-user", taskAddUserForm).then(({ data }) => {
            if (data.code === "0") {
                visiable.rollbackForm = false
                notification['success']({
                    content: '加签成功',
                    meta: `${data.msg}`,
                    duration: 2500,
                    keepAliveOnHover: true
                })
            }
        })
    }
}

function taskTransferSubmit(userIdList: string[]) {
    if (userIdList.length > 0) {
        taskTransferForm.instanceId = route.query.instanceId as string
        taskTransferForm.taskId = route.query.taskId as string
        taskTransferForm.userIdSet = userIdList
        http.post("/workflow/ru/user/task/transfer", taskTransferForm).then(({ data }) => {
            if (data.code === "0") {
                visiable.rollbackForm = false
                notification['success']({
                    content: '移交成功',
                    meta: `${data.msg}`,
                    duration: 2500,
                    keepAliveOnHover: true
                })
            }
        })
    }
}

function cancelInstance() {
    const request = {
        instanceId: route.query.instanceId as string
    }
    http.post("/workflow/ru/instance/cancle", request).then(({ data }) => {
        if (data.code === "0") {
            visiable.rollbackForm = false
            notification['success']({
                content: '取消成功',
                meta: `${data.msg}`,
                duration: 2500,
                keepAliveOnHover: true
            })
        }
    })
}
</script>
<template>
    <n-layout position="absolute" :class="{ 'flow-designer-fullscreen': pageFullScreen }">
        <n-layout-header style="height:48px">
            <div id="design-header" style="position:relative;height:48px;width:100%;">
                <div style="position:absolute;z-index: 500;left:0;display: flex;align-items: center;">
                    <div class="icon" @click="router.back()">
                        <n-icon size="24" color="var(--n-text-color)">
                            <left-outlined />
                        </n-icon>
                    </div>
                    <div style="font-size:16px;height:48px;line-height: 48px;padding-left:12px;">
                        {{ flowStore.modelInfo.modelName }}
                    </div>
                </div>
                <div style="position:absolute;width:100%;height:48px;display: flex;justify-content: center;">
                    <div>
                        <n-tabs v-if="flowStore.mode === '0' || flowStore.mode === '1'"
                            v-model:value="flowStore.currentStep" type="line" :tab-style="{ height: '47px' }">
                            <n-tab name="modelInfo">
                                1、基础信息
                            </n-tab>
                            <n-tab name="formDesign">
                                2、表单设计
                            </n-tab>
                            <n-tab name="flowDesign">
                                3、流程设计
                            </n-tab>
                            <n-tab name="extConfig">
                                4、扩展设置
                            </n-tab>
                        </n-tabs>
                        <n-tabs v-if="['2', '3', '4', '5'].includes(flowStore.mode)" v-model:value="flowStore.currentStep"
                            type="line" :tab-style="{ height: '47px' }">
                            <n-tab name="flowform">
                                1、流程信息
                            </n-tab>
                            <n-tab name="flowView">
                                2、流程图
                            </n-tab>
                        </n-tabs>
                    </div>
                </div>
                <div style="position:absolute;right:0;height:48px;display: flex;align-items: center;padding-right: 7px;">
                    <n-space align="center">
                        <n-button v-if="flowStore.mode === '0'" icon-placement="left" type="primary"
                            @click="flowStore.save()">
                            <template #icon>
                                <n-icon>
                                    <save-outlined />
                                </n-icon>
                            </template>
                            保存
                        </n-button>
                        <n-button v-if="flowStore.mode === '0'" icon-placement="left" type="primary"
                            @click="flowStore.publish()">
                            <template #icon>
                                <n-icon>
                                    <send-outlined />
                                </n-icon>
                            </template>
                            发布
                        </n-button>
                        <n-button-group v-if="flowStore.mode === '3'">
                            <n-button icon-placement="left" type="primary" @click="openApproveForm">
                                <template #icon>
                                    <n-icon>
                                        <edit-outlined />
                                    </n-icon>
                                </template>
                                审批
                            </n-button>
                            <n-popover style="width: 180px;padding: 0;" :content-style="{ padding: 0 }">
                                <template #trigger>
                                    <n-button type="primary">
                                        <template #icon>
                                            <n-icon><ellipsis-outlined /></n-icon>
                                        </template>
                                    </n-button>
                                </template>
                                <n-button @click="openRollbackForm" style="width:100%;height:36px;" quaternary>退回</n-button>
                                <n-button @click="openTaskAddUserForm" style="width:100%;height:36px;"
                                    quaternary>加签</n-button>
                                <n-button @click="openTaskTransferForm" style="width:100%;height:36px;"
                                    quaternary>转交</n-button>
                            </n-popover>
                        </n-button-group>

                        <n-popconfirm
                            v-if="flowStore.mode === '4' && flowStore.instanceInfo?.userId === userStore.account && !['9', '8', '4'].includes(flowStore.instanceInfo.instanceStatus)"
                            @positive-click="cancelInstance">
                            <template #trigger>
                                <n-button type="primary">取消流程</n-button>
                            </template>
                            确定要取消流程吗
                        </n-popconfirm>
                        <div class="icon" @click="pageFullScreen = !pageFullScreen">
                            <n-icon size="24" color="var(--n-text-color)">
                                <arrows-alt-outlined v-if="!pageFullScreen" />
                                <shrink-outlined v-if="pageFullScreen" />
                            </n-icon>
                        </div>
                    </n-space>
                </div>
            </div>
        </n-layout-header>
        <div style="position:absolute;top:48px;bottom:0;left:0;right:0">
            <n-layout-content style="height:100%;background-color: var(--flame-home-content-background-color);">

                <model-config v-if="flowStore.currentStep === 'modelInfo'" />

                <form-designer v-if="flowStore.currentStep === 'formDesign'" />

                <flow-designer v-if="flowStore.currentStep === 'flowDesign'" />

                <ext-config v-if="flowStore.currentStep === 'extConfig'" />

                <div v-if="flowStore.currentStep === 'flowform'" class="flame-container" style="justify-content: center;">
                    <form-viewer @cancel="router.back()" @temp-submit="flowStore.tempSubmit()" :closable="false"
                        @submit="flowStore.formSubmit()" style="margin-right:12px;" />
                    <flow-message style="width:500px" />
                </div>

                <flow-designer v-if="flowStore.currentStep === 'flowView'" />
            </n-layout-content>
        </div>
    </n-layout>
    <approve-form v-model:visiable="visiable.approveForm" :task-id-list="[route.query.taskId as string]" />
    <n-modal v-model:show="visiable.rollbackForm">
        <n-card style="width: 430px" :content-style="{ paddingBottom: '0' }" title="流程退回">
            <n-form ref="rollbackFormRef" :model="rollbackForm" :rules="rollbackFormRules" label-width="92px"
                require-mark-placement="left">
                <n-form-item label="退回节点" path="nodeId">
                    <n-select v-model:value="rollbackForm.nodeId" :options="flowStore.approvalNodeList"
                        label-field="nodeName" value-field="nodeId" placeholder="请选择流程退回节点" />
                </n-form-item>
                <n-form-item label="退回信息" path="rollbackMessage">
                    <n-input v-model:value="rollbackForm.rollbackMessage" type="textarea" placeholder="请输入流程退回信息" />
                </n-form-item>
            </n-form>
            <template #footer>
                <n-space justify="end">
                    <n-button attr-type="button" @click="visiable.rollbackForm = false">取消</n-button>
                    <n-button attr-type="button" type="error" @click="rollbackFormSubmit()">退回</n-button>
                </n-space>
            </template>
        </n-card>
    </n-modal>
    <n-modal v-model:show="visiable.taskAddUserForm">
        <user-selector :value="taskAddUserForm.userIdSet" title="增加审批人" @update:value="taskAddUserFormSubmit"
            @cancel="visiable.taskAddUserForm = false">
            <n-form-item style="margin-top:8px" label="备注信息" path="rollbackMessage">
                <n-input v-model:value="taskAddUserForm.message" type="textarea" placeholder="请输入备注信息" />
            </n-form-item>
        </user-selector>
    </n-modal>
    <n-modal v-model:show="visiable.taskTransferForm">
        <user-selector :value="taskTransferForm.userIdSet" title="转交流程" @update:value="taskTransferSubmit"
            @cancel="visiable.taskTransferForm = false">
            <n-form-item style="margin-top:8px" label="备注信息" path="rollbackMessage">
                <n-input v-model:value="taskTransferForm.message" type="textarea" placeholder="请输入备注信息" />
            </n-form-item>
        </user-selector>
    </n-modal>
</template>
<style scoped>
#design-header .icon {
    width: 48px;
    height: 48px;
    display: flex;
    align-content: center;
    justify-content: center;
    align-items: center;
    flex-wrap: wrap;
    flex-direction: row;
}

#design-header .icon:hover {
    cursor: pointer;
    background-color: var(--flame-icon-background-color);
}

.flow-designer-fullscreen {
    position: fixed;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    width: auto !important;
    height: auto !important;
    z-index: 1000;
}
</style>